{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 从list、dict和str派生\n",
    "\n",
    "## 构建带访问计数器的列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class CounterList(list):\n",
    "    def __init__(self, *args):\n",
    "        super().__init__(*args) # 会调用list的构造函数\n",
    "        self.counter = 0\n",
    "            \n",
    "    # 通过下标访问元素，就会调用此函数\n",
    "    def __getitem__(self, index):\n",
    "        self.counter += 1 # 访问记录\n",
    "        return super(CounterList, self).__getitem__(index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`CounterList`类深深地依赖于其超类（ `list`）的行为。 `CounterList`没有重写的方法（如`append`、 `extend`、 `index`等）都可直接使用。<font color=red>在两个被重写的方法中，使用`super`来调用超类的相应方法</font>，并添加了必要的行为：初始化属性`counter`（在`__init__`中）和更新属性`counter`（在`__getitem__`中）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "c1:  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
      "c1.reverse:  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n",
      "cl.counter:  0\n",
      "c1[4] + c1[2]:  9\n",
      "c1.counter:  2\n"
     ]
    }
   ],
   "source": [
    "c1 = CounterList(range(10))\n",
    "print(\"c1: \", c1)\n",
    "c1.reverse()\n",
    "print(\"c1.reverse: \", c1)\n",
    "del c1[3:6]\n",
    "print(\"cl.counter: \", c1.counter) # 未通过下标访问元素\n",
    "print(\"c1[4] + c1[2]: \", c1[4]+c1[2]) # 通过下标访问元素\n",
    "print(\"c1.counter: \", c1.counter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
